package com.demo.springboot.web;

import com.demo.springboot.dto.FileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class UploadController {

    @Value("${server.upload-dir}")
    private String uploadDir;
    @Value("${server.upload-url}")
    private String uploadUrl;

    @PostMapping("upload")
    public FileUpload upload(@RequestPart("images") MultipartFile file) throws IOException {
        if (file == null) {
            throw new RuntimeException("没有找到要上传的文件");
        }
        // 1.保存目录 2.访问路径(如果需要web访问)
        // 判断保存目录是否存在
        File saveDir = new File(uploadDir);
        if (!saveDir.exists()) {
            saveDir.mkdirs(); // 如果不存在则创建该目录
        }
        // 保存文件名的格式为： 时间戳 + 原始的文件名
        String saveFilename = System.currentTimeMillis() + file.getOriginalFilename();
        System.out.println("保存名称为:" + saveFilename);
        File savePath = new File(saveDir,saveFilename);//保存路径

        try{
            file.transferTo(savePath); // 保存文件到目录
            FileUpload fileUpload = new FileUpload();
            fileUpload.setName(saveFilename);
            fileUpload.setUrl(uploadUrl + saveFilename);
            return fileUpload;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

    }
}
